package cn.open.feishu.alert.support.Handler;

import cn.open.feishu.alert.common.enums.AlertTypeEnum;
import cn.open.feishu.alert.common.model.CardAlertRequest;
import cn.open.feishu.alert.common.model.CardAlertRequest.*;
import cn.open.feishu.alert.common.utils.LinkUtil;
import cn.open.feishu.alert.common.utils.TimeUtil;
import cn.open.feishu.alert.config.FeiShuProperties;
import cn.open.feishu.alert.config.ButtonProperties;
import cn.open.feishu.alert.support.FeishuAlertClient;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 告警基础父类
 * @Author fandy.lin
 * @Date 2021/11/22 10:26 上午
 **/
@Slf4j
@AllArgsConstructor
public abstract class BaseFeishuAlertHandler {
    protected Environment env;
    protected FeiShuProperties feiShuProperties;
    protected ButtonProperties buttonProperties;
    protected FeishuAlertClient feishuAlertClient;

    /**
     * 构建卡片消息告警请求
     *
     * @param alertText
     * @param alertType
     * @param isAt
     * @return
     */
    protected CardAlertRequest buildCardRequest(String alertText, AlertTypeEnum alertType, Boolean isAt) {
        List<Element> elements = new ArrayList<>();
        elements.add(buildCardText(alertText, alertType, isAt));
        buildButtonList(elements, alertType);
        Card card = new Card(elements, buildCardHeader(alertType));
        CardAlertRequest alertReq = CardAlertRequest.builder().card(card).msg_type("interactive").build();
        return alertReq;
    }

    /**
     * 构建卡片消息文本头
     *
     * @param alertType
     * @return
     */
    protected Header buildCardHeader(AlertTypeEnum alertType) {
        String runEnv = env.getProperty("env");
        String content = MessageFormat.format("{0}({1})", alertType.getDesc(), runEnv);
        Title title = Title.builder().tag("plain_text")
                .content(content)
                .build();
        return Header.builder().template("orange").title(title).build();
    }

    /**
     * 构建告警消息文本
     *
     * @param alertText
     * @param alertType
     * @param isAt
     * @return
     */
    protected Element buildCardText(String alertText, AlertTypeEnum alertType, Boolean isAt) {
        StringBuilder textBulider = new StringBuilder();
        if (env.getProperty("app.id") != null) {
            textBulider.append("**").append("服务ID:").append("**\n").append(env.getProperty("app.id"));
        }
        textBulider.append("\n**告警时间:**\n").append(TimeUtil.currentDateFormat());
        if (alertText != null) {
            textBulider.append("\n**").append(alertType == AlertTypeEnum.TEXT_AlERT ? "消息内容:" : "日志内容:")
                    .append("**\n").append(alertText);
        }
        if (isAt && feishuAlertClient.existUser()) {
            textBulider.append("\n**").append("负责人:").append("**\n");
            for (String userId : feishuAlertClient.getUserIds()) {
                textBulider.append(MessageFormat.format("<at id={0}></at>", userId));
            }
        }
        JSONObject text = new JSONObject();
        text.put("content", textBulider.toString());
        text.put("tag", "lark_md");
        return Element.builder().tag("div").text(text).build();
    }

    /**
     * 构建告警消息按钮
     *
     * @param elementList
     * @param alertType
     */
    protected void buildButtonList(List<Element> elementList, AlertTypeEnum alertType) {
        if (!buttonProperties.getKibanaLogEnable() && !buttonProperties.getMonitorEnable()) {
            return;
        }
        Element hr = Element.builder().tag("hr").build();
        List<JSONObject> buttonList = new ArrayList<>();
        if (buttonProperties.getMonitorEnable()) {
            String monitorUrl = LinkUtil.getMonitorUrl(env, buttonProperties);
            buttonList.add(buildButton("Monitor", monitorUrl));
        }
        if (buttonProperties.getKibanaLogEnable() && alertType.equals(AlertTypeEnum.ERROR_LOG_ALERT)) {
            Date now = new Date();
            String kibanaUrl = LinkUtil.getLogUrl(env, buttonProperties, TimeUtil.getRecentMinute(now, -1 * buttonProperties.getLastMinute())
                    , TimeUtil.getRecentMinute(now, buttonProperties.getLastMinute()));
            buttonList.add(buildButton("Kibana", kibanaUrl));
        }
        Element actions = Element.builder().tag("action").actions(buttonList).build();
        elementList.add(hr);
        elementList.add(actions);
    }

    protected JSONObject buildButton(String name, String url) {
        JSONObject kibanaText = new JSONObject();
        kibanaText.put("content", name);
        kibanaText.put("tag", "plain_text");
        JSONObject kibanaObject = new JSONObject();
        kibanaObject.put("tag", "button");
        kibanaObject.put("text", kibanaText);
        kibanaObject.put("type", "primary");
        kibanaObject.put("url", url);
        return kibanaObject;
    }

    /**
     * 获取自定义机器人url
     *
     * @param robotName
     * @return
     */
    protected String getCustomRobotUrl(String robotName) {
        String robotId;
        if (StringUtils.isEmpty(robotName)) {
            robotId = (String) feiShuProperties.getRobotConfig().values().toArray()[0];
        } else {
            robotId = feiShuProperties.getRobotConfig().get(robotName);
        }
        return MessageFormat.format("{0}{1}", feiShuProperties.getCustomizeSendUrl(), robotId);
    }
}